<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>16_await的应用</title>
</head>

<body>
  <script>

    function sendAjax(url, data, index) {
      return new Promise((resolve, reject) => {
        // 实例 xhr
        const xhr = new XMLHttpRequest();
        // 绑定监听
        xhr.onreadystatechange = () => {
          if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) resolve(xhr.response);
            else reject(`第${index}次, 请求出了点问题`);
          }
        };
        // 整理参数
        let str = '';
        for (let key in data) {
          str += `${key}=${data[key]}&`;
        };
        str = str.slice(0, -1);
        // 配置请求
        xhr.open('GET', url + '?' + str);
        xhr.responseType = 'json';
        // 发送请求
        xhr.send();
      });
    };


    !(async () => {
      try {
        const result1 = await sendAjax('https://api.apiopen.top/api', undefined, 1)
        console.log('第1次请求成功了', result1);
        const result2 = await sendAjax('https://api.apiopen.top/api/getShortVideo', undefined, 2)
        console.log('第2次请求成功了', result2);
        const result3 = await sendAjax('https://api.apiopen.top/api/getShortVideo', undefined, 3)
        console.log('第3次请求成功了', result3);
      } catch (error) { 
        console.log(error);
      }
    })()
  </script>
</body>

</html>